import json
import logging
from voice_assistant.my_state import app_state
from voice_assistant.commands.command_executor import process_command
from voice_assistant.voice.wakeword import handle_wake_word_detection
from voice_assistant.event_system import event_system, Events, EventNames

logger = logging.getLogger("handle_message")

async def handle_message(ws):
    """处理接收到的消息"""
    try:
        while True:
            message = await ws.recv()
            # logger.info(f"收到消息: {message}")
            data = json.loads(message)
            
            if data['type'] == 'full_transcript':
                text = data['text'].strip()
                if text:
                    logger.info(f"转写结果: {text}")
                    
                    # 唤醒状态处理
                    if app_state.meeting_recording:
                        # 会议录制模式下，将转写内容追加到会议记录面板
                        append_record(text)
                        continue
                    if app_state.waiting_for_wake:
                        handle_wake_word_detection(text)
                    elif text:
                        response = process_command(text)
                        if response:
                            logger.info(f"命令响应: {response}")
                        app_state.silence_counter = 0
                    
    except Exception as e:
        logger.error(f"消息处理出错: {str(e)}")

def append_record(text):
    cmd = None
    if("停止录音" in text or "暂停录音" in text):
        cmd = EventNames.RECORD_STOP
    elif ("开始录音" in text or "继续录音" in text):
        cmd = EventNames.RECORD_START
    elif ("生成总结" in text):
        cmd = EventNames.RECORD_SUM
    else:
        cmd = EventNames.RECORD_ADD
    
    event_system.publish(Events.MEETING_RECORD, {
        "command": cmd,
        "params": {"text": text}
    })